<?php
/*********************************************************
Function:
Given the keyword, get the urls from the recent 100 tweets.

PHP environment Required!

How to use:
In command line: 
php get_url_from_tw.php [ANYWORD]

Output:

X.Z. Liang
**********************************************************/


//result-per-pages;
$rpp = 100;
//url container
$url_arr = array();
 

//parse the request tag
$keyword = '';
for($i = 1;$i<$argc;$i++){
	$keyword.=$argv[$i]." ";
}
$keyword = rtrim($keyword," ");
$keyword = urlencode($keyword);
 

//download the json string from Twitter Search
$url = "http://search.twitter.com/search.json?q=".$keyword."&rpp=".$rpp."&include_entities=true&result_type=recent";
$json_string = file_get_contents($url);
if(empty($json_string)){
	die("Error in downloading results");
}
$json_lv1 = json_decode($json_string);


//parse the url from JSON
foreach($json_lv1 as $k => $json_lv2){
	if($k == 'results'){
		foreach($json_lv2 as $kk=>$json_lv3){
			if(isset($json_lv3->entities->urls[0])){
				$urls = $json_lv3->entities->urls[0];
  			    insert($urls->expanded_url);
				insert($urls->url);
			}			
			if(isset($json_lv3->text)){
				//to find short urls with in the content 
			    preg_match_all('/(http:\/\/t\.co\/)(.){8}/',$json_lv3->text,$matched_array);
				foreach($matched_array[0] as $k=>$v){
					insert($v);
				}	
 			}
		}
	}
}


//output the result
$url_result = array_keys($url_arr);
foreach($url_result as $v){
	echo $v."\n";
}


/**
 * insert a url to the url_array
 * url is key name to prevent duplicate
**/
function insert($url){
	global $url_arr;
	if(!isset($url_arr[$url])){
		$url_arr[$url]= true;
	}
}
?>